package  org.ttitfly.ttcore.util.query;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;
import org.ttitfly.ttcore.util.annotation.SearchEQLParameter;

public class PropertyParameterResolver implements ParameterResolver {
    private final Object object;

    public PropertyParameterResolver(Object object) {

        this.object = object;
    }

    public Object getValue(String key) {
        if (object == null) {
            return null;
        }

        try {

            for (Field fl : object.getClass().getDeclaredFields()) {
                if (fl.isAnnotationPresent(SearchEQLParameter.class)) {
                    if (fl.getAnnotation(SearchEQLParameter.class).value().equalsIgnoreCase(key)) {
                        key = fl.getName();
                        break;
                    }
                }
            }

            return PropertyUtils.getProperty(object, key);
        } catch (IllegalAccessException e) {
            return null;
        } catch (InvocationTargetException e) {
            return null;
        } catch (NoSuchMethodException e) {
            return null;
        } catch (SecurityException e) {
            return null;
        }
    }

    public Object getObject() {
        return object;
    }

    public boolean isPagable() {
        if (object instanceof Pagable) {
            return true;
        }
        return false;
    }

    public boolean isSortable() {
        if (object instanceof Sortable) {
            return true;
        }
        return false;
    }
}
